package finman.database;

/**
 * User is used by system for authorization.
 * Each user has its name, password and permission.
 * Permission can be either <i>readonly</i>, <i>safe</i> or with <i>full</i> access.
 */
public class User {
	private String name;
	private String password;
	private Permission permission;
	public enum Permission {unknown, readonly, safe, full}

    /**
     * Creates user.
     */
	public User(String userName, String userPassword, Permission userPermission) {
		name = userName;
		password = userPassword;
		permission = userPermission;
	}

    /**
     * Creates user with <i>full</i> access permission.
     */
	public User(String userName, String userPassword) {
		name = userName;
		password = userPassword;
		permission = Permission.full;
	}

    /**
     * Return user name.
     */
	public String getName() { return name; }

    /**
     * Return user password.
     */
	public String getPassword() { return password; }

    /**
     * Return user access permission.
     */
    public Permission getPermission() {
        return permission;
    }

    /**
     * Sets user permission.
     */
    public void setPermission(Permission permission) {
        this.permission = permission;
    }


    @Override
    public int hashCode() {
        int hashCode = 0;
        if (name != null) {
            hashCode += name.hashCode();
        }
        if (password != null) {
            hashCode += password.hashCode();
        }
        return hashCode + permission.ordinal();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof User)) {
            return false;
        }
        User user = (User) obj;
        // check if 'obj' hold an non-null field that is null in this one!
        if (
                ((name == null)&&(user.name != null)) ||
                ((password == null)&&(user.password!= null)) ||
                ((permission == null)&&(user.permission != null))
           )
        {
            return false;
        }
        // whether all field are equal ?
        if ((name != null) && (!name.equals(user.name))) {
            return false;
        }
        if ((password != null) && (!password.equals(user.password))) {
            return false;
        }

        if ((permission != null) && (! permission.equals(user.permission))) {
            return false;
        }
        return true;

    }

    @Override
    public String toString() {
        return String.format("%1s(%2s)", name, permission);
    }


}